<template>
	<div class="app-container">
		<div ref="box1" class="flex-center margin-bottom-10">
			<el-radio-group v-model="searchParams.serviceState" size="medium" class="item-gap" @change="onStateChange">
				<el-radio-button v-for="item in orderStateList" :key="item.id" :label="item.id">
					<el-badge v-if="item.id <= 1 && item.count > 0" :value="item.count" :max="99">
						<span class="margin-right-20">{{ item.name }}</span>
					</el-badge>
					<div v-else class="margin-right-10" style="padding-bottom: 2px;">{{ item.name }}</div>
				</el-radio-button>
			</el-radio-group>
		</div>
		<jk-operation-card ref="box2" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-add-button :permission-prefix="prefix" class="margin-5-0 item-gap" @click="onAddBtn"></jk-add-button>
					<jk-button size="small" icon="el-icon-s-operation" @click="demoSpinConfigDialogState = true">样纱配置</jk-button>
					<!--<jk-report-button :permission-prefix="prefix" class="margin-5-0" :loading="exportLoading" @click="onReportBtn"></jk-report-button>-->
				</div>
				<div class="flex-end-center-wrap">
					<el-checkbox v-model="searchParams.ifTest" label="试产打样" border class="item-gap" size="small"></el-checkbox>
					<jk-search-input v-model="searchParams.customerName" placeholder="客户名称" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.code" placeholder="生产订单号" size="small" class="search-bar-item-code margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.productName" placeholder="品种名称" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.batchCode" placeholder="批号" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-button class="item-gap" @click="onSearchBtn"></jk-search-button>

					<jk-more-search @on-confirm="onSearchBtn" @on-reset="onResetSearchBtn">
						<el-row :gutter="16" class="flex-start-center-wrap">
							<el-col :span="12">
								<jk-search-input v-model="moreSearchParams.plannerName" size="small" placeholder="计划员" clearable class="width-100-percent margin-5-0" @on-enter="onSearchBtn"></jk-search-input>
							</el-col>
							<el-col :span="12">
								<jk-select v-model="moreSearchParams.priorityId" :option-list="priorityList" placeholder="优先级" clearable size="small" class="margin-5-0 width-100-percent"></jk-select>
							</el-col>
							<el-col :span="12">
								<el-date-picker v-model="moreSearchParams.deliveryDateFrom" class="margin-5-0" type="date" align="right" clearable size="small" style="width: 100%;" value-format="yyyy-MM-dd" placeholder="交货开始日期"></el-date-picker>
							</el-col>
							<el-col :span="12">
								<el-date-picker v-model="moreSearchParams.deliveryDateTo" class="margin-5-0" type="date" align="right" clearable size="small" style="width: 100%;" value-format="yyyy-MM-dd" placeholder="交货结束日期"></el-date-picker>
							</el-col>
						</el-row>
					</jk-more-search>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table :loading="tableLoading" :data="tableData" :height="tableHeight + 10">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template v-if="['processList', 'batchCode'].includes(item.keyName)" slot="header">
						<div v-if="item.keyName === 'processList'" class="flex-start-center">
							<div class="margin-right-20">{{ item.title }}:</div>
							<div class="flex-start-center" style="font-size: 12px;">
								<jk-state-bar v-for="(processState, processStateIndex) in processStateList" :key="processStateIndex" class="margin-right-10" :state="processState.id" :state-list="processStateList"></jk-state-bar>
							</div>
						</div>
						<el-row v-if="item.keyName === 'batchCode'" :gutter="6" class="flex-start-center">
							<el-col :span="12">批号</el-col>
							<!--<el-col style="text-align: right;" :span="2"><span>包数</span></el-col>
							<el-col style="text-align: right;" :span="3"><span>重量(吨)</span></el-col>
							<el-col style="text-align: right;" :span="2"><span>已入库</span></el-col>
							<el-col style="text-align: right;" :span="2"><span>待入库</span></el-col>-->
							<el-col :span="4"><span>纸管颜色</span></el-col>
							<el-col :span="4"><span>腰绳颜色</span></el-col>
							<el-col :span="4"><span>标签颜色</span></el-col>
						</el-row>
					</template>
					<template slot-scope="scope">
						<jk-state-bar v-if="item.keyName === 'priorityName'" :state="scope.row.priorityId" :state-list="priorityList"></jk-state-bar>
						<span v-else-if="item.keyName === 'code'" class="link-style" @click="onDetailBtn(scope.row)">{{ scope.row.code }}</span>
						<span v-else-if="item.keyName === 'ifTest'">{{ scope.row.ifTest ? '试产打样' : '正式生产' }}</span>
						<span v-else-if="item.keyName === 'awaitMachineNameList'">
							<el-row>
								<el-col><span class="text-ellipsis" style="display: block;white-space: normal;word-break: break-word;overflow-wrap: break-word;">{{ scope.row.awaitMachineNameList.join(',') }}</span></el-col>
							</el-row>
						</span>
						<span v-else-if="item.keyName === 'openMachineNameList'">
							<el-row>
								<el-col><span class="text-ellipsis" style="display: block;white-space: normal;word-break: break-word;overflow-wrap: break-word;">{{ scope.row.openMachineNameList.join(',') }}</span></el-col>
							</el-row>
						</span>
						<jk-state-bar v-else-if="item.keyName === 'serviceState'" :state="scope.row.serviceState" :state-list="orderStateList"></jk-state-bar>
						<div v-else-if="item.keyName === 'batchCode'">
							<el-row
								v-for="(batchItem, batchIndex) in scope.row.productOrderBatchList || []"
								:key="batchIndex"
								:gutter="6"
							>
								<el-col :span="12"><span class="text-ellipsis">{{ batchIndex + 1 }}、{{ batchItem.batchCode }}</span></el-col>
								<!--<el-col :span="2"><div style="text-align: right;" class="text-ellipsis">{{ batchItem.packNum || 0 }}</div></el-col>
								<el-col :span="3"><div style="text-align: right;" class="text-ellipsis">{{ batchItem.packQty || 0 }}</div></el-col>
								<el-col :span="2"><div style="text-align: right;" class="text-ellipsis">{{ batchItem.packWarehousingNum || 0 }}</div></el-col>
								<el-col :span="2"><div style="text-align: right;" class="text-ellipsis">{{ batchItem.packWaitWarehousingNum || 0 }}</div></el-col>-->
								<el-col :span="4"><div class="">{{ filterColor(batchItem.paperTubeList || []) }}</div></el-col>
								<el-col :span="4"><div class="">{{ filterColor(batchItem.waistPopeList || []) }}</div></el-col>
								<el-col :span="4"><div class="">{{ filterColor(batchItem.labelColorList || []) }}</div></el-col>
							</el-row>
						</div>
						<div v-else-if="item.keyName === 'percentage'" class="flex-center">
							<jk-progress :show-text="false" :show-custom-text="true" :custom-text-style="{fontSize: '12px'}" :stroke-width="6" type="circle" color="#19be6b" :width="40" :percentage="scope.row.percentage || 0"></jk-progress>
						</div>
						<div v-else-if="item.keyName === 'processList'" style="cursor: pointer;">
							<processSteps
								:state-list="processStateList"
								:process-list="scope.row.prdNoteProcessAllotmentQuantityList"
							></processSteps>
						</div>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="250">
					<template slot-scope="scope">
						<div class="flex-start-center">
							<jk-button size="mini" icon="el-icon-guide" :disabled="scope.row.serviceState === 3" class="item-gap" type="success" @click="onPlanShareBtn(scope.row)">批号</jk-button>
							<!--<jk-delete-button :permission-prefix="prefix" @on-confirm="onDeleteBtn(scope.row)"></jk-delete-button>-->
							<jk-edit-button :permission-prefix="prefix" :disabled="scope.row.serviceState === 3" class="item-gap" @click="onEditBtn(scope.row)"></jk-edit-button>
							<el-dropdown trigger="click" @command="onDropdownChange($event, scope.row)">
								<el-button type="primary" size="mini" class="el-dropdown-link">
									更多<i class="el-icon-arrow-down el-icon--right"></i>
								</el-button>
								<el-dropdown-menu slot="dropdown">
									<el-dropdown-item
										v-for="(item) in dropdownOption"
										:key="item.code"
										:command="item.code"
										:divided="item.divided"
										:disabled="item.allowState || item.allowState === 0 ? scope.row.serviceState !== item.allowState : false"
										:style="{
											'display': !item.isShow ? 'none' : 'block',
											'text-decoration': getPermission([`${prefix}:${item.permissionName}`]) ? '' : 'line-through'
										}"
									>
										<span :class="`${item.icon} item-gap`"></span>
										<span>{{ item.name }}</span>
									</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box3" class="flex-end-center margin-top-10">
				<!--<total-detail-popover :form-data="totalData"></total-detail-popover>-->
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<share-plan-dialog
			:data-id="dataId"
			:dialog-state="sharePlanDialogState"
			@on-visible-change="onVisibleChange"
			@on-refresh="onFinish"
		></share-plan-dialog>
		<share-category-dialog
			:data-item="selectedRowItem"
			:dialog-state="shareCategoryDialogState"
			@on-visible-change="onVisibleChangeOfShareCategory"
			@on-finish="onFinishOfShareCategory"
		></share-category-dialog>
		<demoSpinConfigDialog
			:dialog-state="demoSpinConfigDialogState"
			@on-visible-change="onVisibleChangeOfDemoSpinConfigDialog"
			@on-finish="onFinishOfDemoSpinConfigDialog"
		></demoSpinConfigDialog>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, tipsBar } from '/src/utils/jk/jk-tool';
    import {
        productionPrdOrderDelete,
        productionPrdOrderPage,
        productionPrdOrderExportExcel,
        productionPrdOrderGetStateCount,
        productionPrdOrderClose,
        productionPrdOrderClearClose
    } from '/src/api/production/order';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import sharePlanDialog from './components/share-plan-dialog';
    import {
        orderPriorityList,
        orderStateList,
        productionStateList,
        productionTypeList
    } from '../../../utils/jk/status-option-list';
    import permissionMixin from '../../../mixins/permission-mixin';
    import { productionPrdOrderSum } from '../../../api/production/productionMonitor';
    import totalDetailPopover from '../../statisticAnalysis/orderMonitorReport/total-detail-popover';
    import { pushOrderToWxUser } from '../../../api/production/xsDailyGroupYieldNew';
    import shareCategoryDialog from './components/share-category-dialog';
    import processSteps from './components/process-steps';
    import jkProgress from '../../jk-components/jk-progress';
    import demoSpinConfigDialog from './components/demo-spin-config-dialog2';
    import supplementaryPlanMx from './components/form-box/supplementaryPlanMx';
    export default {
        name: 'PrdOrder',
        components: {
            demoSpinConfigDialog,
            jkProgress,
            processSteps,
            shareCategoryDialog,
            totalDetailPopover,
            sharePlanDialog
        },
        mixins: [calHeight, getMenuColumn, handlerCache, permissionMixin, supplementaryPlanMx],
        data() {
            return {
                prefix: 'production:prdOrder',
                apiItem: {
                    'page': productionPrdOrderPage,
                    'exportExcel': productionPrdOrderExportExcel,
                    'delete': productionPrdOrderDelete
                },
                demoSpinConfigDialogState: false,
                shareCategoryDialogState: false,
                totalData: {},
                orderItem: null,
                productionTypeList: productionTypeList,
                selectedRowItem: {},
                sharePlanDialogState: false,
                orderStateList: [
                    ...orderStateList,
                    { id: -1, name: '全部' }
                ],
                productionStateList: productionStateList,
                dataId: null,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                totalCount: 0,
                processStateList: [
                    { id: -1, name: '待下达', color: '#c0c4cc' },
                    { id: 0, name: '待生产', color: '#ff9900' },
                    { id: 1, name: '生产中', color: '#2d8cf0' },
                    { id: 2, name: '生产完成', color: '#19be6b' }
                ],
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    code: '',
                    ifTest: false,
                    productName: '',
                    batchCode: '',
                    customerName: '',
                    serviceState: 0
                },
                moreSearchParams: {
                    deliveryDateTo: '',
                    deliveryDateFrom: '',
                    priorityId: null,
                    plannerName: ''
                },
                priorityList: orderPriorityList,
                dropdownOption: [
                    { code: 'QUERY', name: '详情', isShow: true, permissionName: 'query', icon: 'el-icon-view', allowState: null, api: null },
                    { code: 'CLOSE', name: '完成', isShow: true, permissionName: 'close', divided: true, icon: 'el-icon-finished', allowState: null, api: productionPrdOrderClose },
                    { code: 'CANCEL_CLOSE', name: '撤销完成', permissionName: 'close', isShow: true, icon: 'el-icon-circle-close', allowState: 3, api: productionPrdOrderClearClose },
                    // { code: 'SEND_OUT_GOODS', name: '发货', isShow: true, permissionName: 'delete', icon: 'el-icon-truck', allowState: null, api: null },
                    // { code: 'SEND_WX_MSG', name: '推送公众号', isShow: true, permissionName: 'delete', icon: 'el-icon-s-promotion', allowState: null, api: null },
                    { code: 'DELETE', name: '删除', isShow: true, permissionName: 'delete', icon: 'el-icon-delete', allowState: 0, api: productionPrdOrderDelete }
                ]
            };
        },
        mounted() {
            // 来自补开台清单时，默认将品种查询出来
            if (this.$route.query.productName) this.$set(this.searchParams, 'productName', this.$route.query.productName);
            this.getDependentData();
        },
        methods: {
            onFinishOfDemoSpinConfigDialog(e) {
                this.demoSpinConfigDialogState = e;
            },
            onVisibleChangeOfDemoSpinConfigDialog(e) {
                this.demoSpinConfigDialogState = e;
            },
            filterColor(list) {
                const arr = list.filter(x => x.auditState);
                const str = arr.map(x => x.name).join(',');
                return str;
            },
            onStateChange() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPlanShareBtn(row) {
                this.dataId = row.id;
                this.sharePlanDialogState = true;

                // this.dataId = row.id;
                // this.selectedRowItem = row;
                // this.shareCategoryDialogState = true;
            },
            onFinishOfShareCategory() {
                this.shareCategoryDialogState = false;
                this.$nextTick(() => {
                    this.sharePlanDialogState = true;
                });
            },
            onVisibleChangeOfShareCategory(e) {
                this.shareCategoryDialogState = e;
            },
            onResetSearchBtn() {
                Object.assign(this.$data.moreSearchParams, this.$options.data().moreSearchParams);
            },
            onDropdownChange(type, row) {
                const optionItem = this.dropdownOption.find(x => x.code === type);
                if (this.getPermission([`${this.prefix}:${optionItem.permissionName}`])) {
                    if (optionItem) {
                        if (optionItem.code === 'QUERY') {
                            this.onDetailBtn({ id: row.id });
                        } else if (optionItem.code === 'SEND_WX_MSG') {
                            // 推送微信
                            this.orderItem = row;
                            this.pushOrderToUserRequest(row);
                        } else {
                            this.$confirm(`确定"${optionItem.name}"吗？`, '提示', { type: 'warning' }).then(() => {
                                optionItem.api({ id: row.id }).then(res => {
                                    if (res.data.status === 200) {
                                        this.getListRequest();
                                    }
                                });
                            }).catch(() => {});
                        }
                    }
                } else {
                    tipsBar(this, 'custom', 'warning', '无操作权限!');
                }
            },
            pushOrderToUserRequest(row) {
                if (row.customerOpenIds.length) {
                    const params = {
                        orderCode: row.code,
                        productName: row.productName,
                        batchCode: row.productOrderBatchList.map(x => x.batchCode).join(),
                        orderQty: row.orderQty,
                        completionQty: row.completionQty,
                        openList: row.customerOpenIds
                    };
                    pushOrderToWxUser(params).then(res => {
                        if (res.data.status === 200) {
                            tipsBar(this, 'custom', 'success', '发送成功!');
                        }
                    });
                } else {
                    tipsBar(this, 'custom', 'warning', '没有微信用户绑定该客户, 无法推送!');
                }
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            onFinish() {
                // this.sharePlanDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                this.sharePlanDialogState = e;
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },

            getStateBarCountRequest() {
                return productionPrdOrderGetStateCount().then(res => {
                    if (res.data.status === 200) {
                        this.orderStateList = this.orderStateList.map(x => {
                            x.count = 0;
                            res.data.res.forEach(k => {
                                if (x.id === k.auditState) {
                                    x.count = k.count;
                                }
                            });
                            return x;
                        });
                    } else {
                        this.orderStateList = this.orderStateList.map(x => {
                            x.count = 0;
                            return x;
                        });
                    }
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                await this.getMenuColumnListRequest();
                await this.getListRequest();
                this.getErrorInfoRequest({ state: 0 });
                this.tableLoading = false;
            },
            onDetailBtn(row) {
                this.dataId = row.id;
                this.$toOtherRouter({
                    name: 'detailPrdOrder',
                    query: {
                        id: row.id
                    }
                });
            },
            getTotalDataRequest() {
                const params = JSON.parse(JSON.stringify(this.searchParams));
                delete params.count;
                delete params.pageNo;
                delete params.pageSize;
                return productionPrdOrderSum(params).then(res => {
                    if (res.data.status === 200) {
                        this.totalData = res.data.res || {};
                    }
                });
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                // this.getTotalDataRequest();
                const params = { ...JSON.parse(JSON.stringify(this.moreSearchParams)), ...JSON.parse(JSON.stringify(this.searchParams)) };
                if (params.serviceState === -1) {
                    params.serviceState = null;
                }
                return this.apiItem['page'](params).then(res => {
                    this.getStateBarCountRequest();
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res ? res.data.res.map(x => {
                            return x;
                        }) : [];
                        this.totalCount = res.data.count;
                    }
                });
            },
            /** 新增按钮操作 */
            onAddBtn() {
                this.$toOtherRouter({ name: 'addPrdOrder' });
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.dataId = row.id;
                this.$toOtherRouter({
                    name: 'editPrdOrder',
                    query: {
                        id: row.id
                    }
                });
            },

            /** 删除按钮操作 */
            onDeleteBtn(row) {
                this.apiItem['delete']({ id: row.id }).then((res) => {
                    if (res.data.status === 200) {
                        this.getListRequest();
                        this.$tipsBar(this, 'delete');
                    }
                }).catch(() => {});
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = { ...this.searchParams };
                params.pageNo = null;
                params.pageSize = null;
                this.$confirm('是否确认导出所有数据项?', { type: 'warning' }).then(() => {
                    this.exportLoading = true;
                    return this.apiItem['exportExcel'](params);
                }).then(res => {
                    if (res.data.status === 200) {
                        this.$download.excel(res, `${this.$route.meta.name}.xls`);
                        this.exportLoading = false;
                    }
                }).catch(() => {});
            }
        }
    };
</script>
